#coding=utf-8

import time,mmap
import numpy
from threading import Thread
import fcntl
import posix_ipc
import cv2
import signal
import os

from multiprocessing import Manager, Process, Queue, Value

import ctypes  
ll = ctypes.cdll.LoadLibrary   
lib = ll("../libs/libHiRTPCommon.so")   

sempty = None
sfull = None
is_exit = False

share_path = "/tmp/hi/video_test_111_bgr"

os.system('rm bmp/*')

image_queue = Queue()

def sigint_handler(signum, frame):
    global sempty
    global sfull
    global is_exit
    global IsExit
    if is_exit == True:
        exit(-1)
        return
    is_exit = True
    if sempty != None:
        sempty.close()
    if sfull != None:
        sfull.close()

    print('catched interrupt signal!')
    time.sleep(1)
    exit(-1)

signal.signal(signal.SIGINT, sigint_handler)
signal.signal(signal.SIGHUP, sigint_handler)
signal.signal(signal.SIGTERM, sigint_handler)
        
def pic_receive_thread():
    shape =  (1920, 1080, 3)
    frequency = 16
    interval = 1.0 / (25*frequency)
    
    quit = None
    prefix = share_path
    prefix = "/" + prefix.replace("/", ".")
    empty_key = prefix + ".empty"
    full_key = prefix + ".full"
    sempty = posix_ipc.Semaphore(empty_key, posix_ipc.O_CREAT, initial_value=1)
    sfull = posix_ipc.Semaphore(full_key, posix_ipc.O_CREAT, initial_value=0)
    print(empty_key)
    print(full_key)
    global is_exit
    shape =  (1920, 1080, 3)
    index = 0
    try:
        with open(share_path, "r+b") as f:
            mm = mmap.mmap(f.fileno(), 0)
            while is_exit != True:
                try:
                    res = sfull.acquire(0.2)
                except Exception as e:
                    print('acquire full error.' + str(e))
                    continue
                if index % frequency == 0:
                    fcntl.flock(f, fcntl.LOCK_EX)
                    img = numpy.ndarray(shape=shape, dtype=numpy.uint8, buffer=mm).copy()
                    fcntl.flock(f, fcntl.LOCK_UN)
                sempty.release()
                if index % frequency == 0:
                    image_queue.put((0, img))
                    index = 0
                index = index + 1
                #time.sleep(interval)
    except Exception as e:
        sempty.release()
        print("except:" + str(e))
    print('pic recevie quit')    
    sempty.close()
    sfull.close()
    sempty = None
    sfull = None


      
def pic_save_thread():
    save_index = 0
    global is_exit
    while is_exit != True:
        sn, img = image_queue.get()
        save_index = save_index + 1
        '''
        if save_index < 100:        
            print(str(img.shape) + ";" + str(img.dtype) + ";" )
            cv2.imwrite("bmp/" + str(save_index) + '.bmp', img)
            print("save index:" + str(save_index) + ";" + "bmp/" + str(save_index) + '.bmp')
        else:
            is_exit = True
            print("exit")
        '''
        try:
            char_p_test = bytes("./bmp/" + str(save_index % 200) + '.bmp',"utf8")
            lib.hi_saveBmp(char_p_test, img.tobytes(), 1920, 1080)
            print("save pic end")
        except Exception as e:
            print('save pic exception:' + str(e))
        save_index = save_index + 1
    print('pic save quit')    
    
receive_thread = Thread(target=pic_receive_thread)
save_thread = Thread(target=pic_save_thread)
save_thread.start()
receive_thread.start()

save_thread.join()
receive_thread.join()

print('DataTransport quit')
